<template>
  <div class="maintenance-plan-page">
    <div class="page-header">
      <h2>保养计划管理</h2>
      <p>管理系统中的设备保养计划</p>
    </div>

    <div class="operation-section">
      <el-card class="search-card">
        <div class="search-header">
          <h3>搜索条件</h3>
          <el-button type="info" plain @click="handleReset">重置</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchForm.keyword"
              placeholder="设备名称/编码"
              clearable
              prefix-icon="Search"
            />
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 100%"
            >
              <el-option label="待执行" :value="0" />
              <el-option label="执行中" :value="1" />
              <el-option label="已完成" :value="2" />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" class="search-btn" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
          </el-col>
        </el-row>
      </el-card>

      <div class="toolbar">
        <el-button type="primary" class="toolbar-btn" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增保养计划
        </el-button>
        <el-button class="toolbar-btn" @click="loadMaintenancePlanList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        class="plan-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          prop="deviceName"
          label="设备名称"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-link type="primary" @click="handleView(scope.row)">
              {{ scope.row.deviceName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="deviceCode" label="设备编码" min-width="120" />
        <el-table-column
          prop="maintenanceProject"
          label="保养项目"
          min-width="120"
        />
        <el-table-column prop="maintenanceLevel" label="保养级别" width="100" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" />
        <el-table-column
          prop="estimatedCost"
          label="预计费用(元)"
          width="120"
          align="right"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">待执行</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="info"
              >执行中</el-tag
            >
            <el-tag v-else type="success">已完成</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
              <el-button
                size="small"
                type="warning"
                link
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="scope.row.status === 0"
                size="small"
                type="success"
                link
                @click="handleExecute(scope.row)"
              >
                执行
              </el-button>
              <el-button
                size="small"
                type="danger"
                link
                @click="handleDeleteWithCheck(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
      class="plan-dialog"
    >
      <el-form
        ref="formRef"
        :model="planForm"
        :rules="formRules"
        label-width="120px"
        class="plan-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备ID" prop="equipmentId">
              <el-input
                v-model.number="planForm.equipmentId"
                placeholder="请输入设备ID"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保养项目" prop="maintenanceProject">
              <el-input
                v-model="planForm.maintenanceProject"
                placeholder="请输入保养项目"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保养级别" prop="maintenanceLevel">
              <el-select
                v-model="planForm.maintenanceLevel"
                placeholder="请选择保养级别"
                style="width: 100%"
              >
                <el-option label="一级保养" value="一级保养" />
                <el-option label="二级保养" value="二级保养" />
                <el-option label="三级保养" value="三级保养" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input
                v-model="planForm.responsiblePerson"
                placeholder="请输入负责人"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="startTime">
              <el-date-picker
                v-model="planForm.startTime"
                type="datetime"
                placeholder="请选择计划开始时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="endTime">
              <el-date-picker
                v-model="planForm.endTime"
                type="datetime"
                placeholder="请选择计划结束时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计费用(元)" prop="estimatedCost">
              <el-input
                v-model.number="planForm.estimatedCost"
                placeholder="请输入预计费用"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保养周期" prop="maintenanceCycle">
              <el-input
                v-model="planForm.maintenanceCycle"
                placeholder="请输入保养周期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="planForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="viewDialogVisible"
      title="保养计划详情"
      width="60%"
      class="view-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备ID">
          {{ viewPlan.equipmentId }}
        </el-descriptions-item>
        <el-descriptions-item label="保养项目">
          {{ viewPlan.maintenanceProject }}
        </el-descriptions-item>
        <el-descriptions-item label="保养级别">
          {{ viewPlan.maintenanceLevel }}
        </el-descriptions-item>
        <el-descriptions-item label="负责人">
          {{ viewPlan.responsiblePerson }}
        </el-descriptions-item>
        <el-descriptions-item label="计划开始时间">
          {{ formatDate(viewPlan.startTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="计划结束时间">
          {{ formatDate(viewPlan.endTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="预计费用(元)">
          {{ viewPlan.estimatedCost }}
        </el-descriptions-item>
        <el-descriptions-item label="保养周期">
          {{ viewPlan.maintenanceCycle }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="viewPlan.status === 0" type="warning">待执行</el-tag>
          <el-tag v-else-if="viewPlan.status === 1" type="info">执行中</el-tag>
          <el-tag v-else type="success">已完成</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ viewPlan.remark }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="executeDialogVisible"
      title="执行保养计划"
      width="50%"
      :close-on-click-modal="false"
      class="execute-dialog"
    >
      <el-form
        ref="executeFormRef"
        :model="executeForm"
        :rules="executeFormRules"
        label-width="120px"
        class="execute-form"
      >
        <el-form-item label="保养项目" prop="maintenanceProject">
          <el-input
            v-model="executeForm.maintenanceProject"
            placeholder="请输入保养项目"
            disabled
          />
        </el-form-item>

        <el-form-item label="实际费用(元)" prop="actualCost">
          <el-input
            v-model.number="executeForm.actualCost"
            placeholder="请输入实际费用"
            type="number"
          />
        </el-form-item>

        <el-form-item label="执行人" prop="executor">
          <el-input v-model="executeForm.executor" placeholder="请输入执行人" />
        </el-form-item>

        <el-form-item label="执行备注" prop="remark">
          <el-input
            v-model="executeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入执行备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="executeDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="executeLoading"
            @click="handleExecuteSubmit"
          >
            确定执行
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Refresh,
  Document,
  Clock,
  Setting,
  Check
} from "@element-plus/icons-vue";
import moment from "moment";
import type {
  MaintenancePlan,
  MaintenancePlanVo,
  MaintenancePlanQuery,
  MaintenancePlanAdd,
  MaintenancePlanUpdate,
  MaintenancePlanExecute
} from "@/api/maintenancePlan";
import {
  getMaintenancePlanList,
  getMaintenancePlanDetail,
  addMaintenancePlan,
  updateMaintenancePlan,
  deleteMaintenancePlan,
  executeMaintenancePlan
} from "@/api/maintenancePlan";

defineOptions({ name: "MaintenancePlan" });

const loading = ref(false);
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const executeDialogVisible = ref(false);
const dialogTitle = ref("新增保养计划");
const formRef = ref();
const executeFormRef = ref();
const submitLoading = ref(false);
const executeLoading = ref(false);
const multipleSelection = ref<MaintenancePlanVo[]>([]);

const searchForm = reactive<MaintenancePlanQuery>({
  page: 1,
  limit: 10,
  keyword: "",
  status: undefined
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

const tableData = ref<MaintenancePlanVo[]>([]);

const planForm = reactive<MaintenancePlan>({
  equipmentId: undefined,
  maintenanceProject: "",
  startTime: "",
  endTime: "",
  estimatedCost: undefined,
  maintenanceCycle: "",
  maintenanceLevel: "",
  status: 0,
  responsiblePerson: ""
});

const viewPlan = reactive<MaintenancePlan>({
  equipmentId: undefined,
  maintenanceProject: "",
  startTime: "",
  endTime: "",
  estimatedCost: undefined,
  maintenanceCycle: "",
  maintenanceLevel: "",
  status: 0,
  responsiblePerson: ""
});

const executeForm = reactive<MaintenancePlanExecute>({
  id: undefined,
  maintenanceProject: "",
  actualCost: undefined,
  executor: "",
  remark: ""
});

const formRules = reactive({
  equipmentId: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
  maintenanceProject: [
    { required: true, message: "请输入保养项目", trigger: "blur" }
  ],
  maintenanceLevel: [
    { required: true, message: "请选择保养级别", trigger: "change" }
  ],
  responsiblePerson: [
    { required: true, message: "请输入负责人", trigger: "blur" }
  ],
  startTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" }
  ],
  endTime: [
    { required: true, message: "请选择计划结束时间", trigger: "change" }
  ],
  estimatedCost: [
    { required: true, message: "请输入预计费用", trigger: "blur" }
  ]
});

const executeFormRules = reactive({
  actualCost: [{ required: true, message: "请输入实际费用", trigger: "blur" }],
  executor: [{ required: true, message: "请输入执行人", trigger: "blur" }]
});

const formatDate = (date: string) => {
  if (!date) return "";
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
};

onMounted(() => {
  loadMaintenancePlanList();
});

const loadMaintenancePlanList = async () => {
  loading.value = true;
  try {
    const params: MaintenancePlanQuery = {
      ...searchForm,
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    const res = await getMaintenancePlanList(params);
    if (res.code === 0 && res.data) {
      tableData.value = res.data.list || [];
      pagination.total = res.data.total || 0;
    } else {
      ElMessage.error(res.message || "获取保养计划列表失败");
    }
  } catch (error) {
    console.error("获取保养计划列表失败:", error);
    ElMessage.error("获取保养计划列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.currentPage = 1;
  loadMaintenancePlanList();
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.status = undefined;
  handleSearch();
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadMaintenancePlanList();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadMaintenancePlanList();
};

const handleSelectionChange = (val: MaintenancePlanVo[]) => {
  multipleSelection.value = val;
};

const showAddDialog = () => {
  dialogTitle.value = "新增保养计划";
  dialogVisible.value = true;
  resetForm();
};

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(planForm, {
    equipmentId: undefined,
    maintenanceProject: "",
    startTime: "",
    endTime: "",
    estimatedCost: undefined,
    maintenanceCycle: "",
    maintenanceLevel: "",
    status: 0,
    responsiblePerson: ""
  });
};

const handleView = async (row: MaintenancePlanVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的保养计划ID");
    return;
  }

  try {
    const response = await getMaintenancePlanDetail(Number(row.id));
    if (response.code === 0 && response.data) {
      Object.assign(viewPlan, response.data);
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取保养计划详情失败");
    }
  } catch (error) {
    console.error("获取保养计划详情异常:", error);
    ElMessage.error("获取保养计划详情失败");
  }
};

const handleEdit = async (row: MaintenancePlanVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的保养计划ID");
    return;
  }

  try {
    const response = await getMaintenancePlanDetail(Number(row.id));
    if (response.code === 0 && response.data) {
      Object.assign(planForm, response.data);
      dialogTitle.value = "编辑保养计划";
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取保养计划详情失败");
    }
  } catch (error) {
    console.error("获取保养计划详情异常:", error);
    ElMessage.error("获取保养计划详情失败");
  }
};

const handleDeleteWithCheck = (row: MaintenancePlanVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的保养计划ID");
    return;
  }

  handleDelete(Number(row.id));
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定要删除该保养计划吗？删除后无法恢复。", "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteMaintenancePlan(id);
        if (response.code === 0) {
          ElMessage.success("删除成功");
          loadMaintenancePlanList();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除保养计划异常:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        let response;
        if (dialogTitle.value === "新增保养计划") {
          const addData: MaintenancePlanAdd = {
            equipmentId: planForm.equipmentId!,
            startTime: planForm.startTime,
            maintenanceProject: planForm.maintenanceProject,
            maintenanceLevel: planForm.maintenanceLevel,
            remark: planForm.remark,
            endTime: planForm.endTime,
            estimatedCost: planForm.estimatedCost!,
            maintenanceCycle: planForm.maintenanceCycle,
            responsiblePerson: planForm.responsiblePerson
          };
          response = await addMaintenancePlan(addData);
        } else {
          const updateData: MaintenancePlanUpdate = {
            id: planForm.id!,
            equipmentId: planForm.equipmentId!,
            startTime: planForm.startTime,
            maintenanceItem: planForm.maintenanceProject,
            maintenanceLevel: planForm.maintenanceLevel,
            remark: planForm.remark,
            endTime: planForm.endTime,
            estimatedCost: planForm.estimatedCost!,
            responsiblePerson: planForm.responsiblePerson
          };
          response = await updateMaintenancePlan(updateData);
        }

        if (response.code === 0) {
          ElMessage.success(
            dialogTitle.value === "新增保养计划" ? "新增成功" : "更新成功"
          );
          dialogVisible.value = false;
          loadMaintenancePlanList();
        } else {
          ElMessage.error(
            response.message ||
              (dialogTitle.value === "新增保养计划" ? "新增失败" : "更新失败")
          );
        }
      } catch (error) {
        console.error(
          dialogTitle.value === "新增保养计划"
            ? "新增保养计划异常:"
            : "更新保养计划异常:",
          error
        );
        ElMessage.error(
          dialogTitle.value === "新增保养计划" ? "新增失败" : "更新失败"
        );
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const handleExecute = (row: MaintenancePlanVo) => {
  if (!row.id || isNaN(Number(row.id))) {
    ElMessage.error("无效的保养计划ID");
    return;
  }

  executeForm.id = row.id;
  executeForm.maintenanceProject = row.maintenanceProject || "";
  executeForm.actualCost = undefined;
  executeForm.executor = "";
  executeForm.remark = "";

  if (executeFormRef.value) {
    executeFormRef.value.resetFields();
  }

  executeDialogVisible.value = true;
};

const handleExecuteSubmit = async () => {
  if (!executeFormRef.value) return;

  executeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      executeLoading.value = true;
      try {
        const executeData: MaintenancePlanExecute = {
          id: executeForm.id!,
          maintenanceProject: executeForm.maintenanceProject,
          actualCost: executeForm.actualCost,
          executor: executeForm.executor,
          remark: executeForm.remark
        };

        const response = await executeMaintenancePlan(executeData);
        if (response.code === 0) {
          ElMessage.success("执行成功");
          executeDialogVisible.value = false;
          loadMaintenancePlanList();
        } else {
          ElMessage.error(response.message || "执行失败");
        }
      } catch (error) {
        console.error("执行保养计划异常:", error);
        ElMessage.error("执行失败");
      } finally {
        executeLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.maintenance-plan-page {
  padding: 20px;
  background-color: #f5f6f7;
  min-height: calc(100vh - 80px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #606266;
}

.operation-section {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 16px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.search-header h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

:deep(.el-row) .el-col {
  margin-bottom: 16px;
}

.search-btn {
  width: 100%;
  height: 32px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-btn {
  height: 36px;
}

.table-card {
  margin-bottom: 20px;
}

.plan-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.plan-table :deep(.el-table__row:hover) {
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 0;
}

.plan-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

.plan-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.view-dialog :deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 500;
}

.execute-dialog :deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

.execute-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
}

@media (max-width: 768px) {
  .maintenance-plan-page {
    padding: 12px;
  }

  .toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style>
